#!/bin/bash

. tcpnode.conf
if [ ! "$localdir" ]; then
	exit 1
fi
if [ ! "$webdir" ]; then
	exit 2
fi

#webdir=http://gitee.com/breaker0727/n2n-supernode
#localdir=/storage/n2n-supernode
localnode=$localdir/tcpnode.txt
getwebnode="wget -O - -q $webdir/raw/master/tcpnode.txt"

fgetremoteport()
{
if [ "$1" ]; then
 port=$($findhole $1 $2 )
 if [ "$port" ]; then
 	echo $port
 fi
fi
}
initnode(){
	node=$(cat $localnode)
	echo $node >$tmpnode
}
getnode(){
	echo $(cat $tmpnode)
}
setnode(){
	echo "setnode="$1
	echo $1 >$tmpnode
	echo $1 >$localnode
}
checksync(){
	node1=$($getwebnode)
	node2=$(getnode)
	if [ "$node1" ]; then
		if [ "$node1" == "$node2" ]; then
			echo "ok"
		else
			echo "no"
		fi
	fi
}
updateweb(){
	echo "updateweb ..."
	$n2nsyncweb
}
startapp(){
	node=$(getnode)
	${app1}
}
stopapp(){
	kill -9 $($pidapp)
}
updatenode(){
	echo "getip"
	ip=$($getip)
	echo "ip="$ip
	if [ "$ip" ]; then
		echo "get port"
		port=$(fgetremoteport $ip $localport)
		if [ "$port" ]; then
			node=$ip":"$port
			setnode $node
		fi
	fi
}
restartapp(){
	stopapp
	updatenode
	startapp
}
auto_tcp(){
	initnode
	i=0
	err=0
	while true
	do
		node=$(getnode)
		echo "node"=$node
		resp=$($testlink $node $localport)
		echo "resp"=$resp
		if [ "$resp" = "ok" ]; then
			if [ "$($pidapp)" ]; then
				echo "sleep"
				sleep 30
				let i+=1
				echo "i="$i
				if [ $i -ge 5 ]; then
					let i=0
					resp=$(checksync)
					if [ "$resp" == "no" ]; then
						updateweb
					fi
				fi
			else
				echo "start"				
				startapp
			fi
		else
			let err+=1
			if [ $err -ge 5 ]; then
				let err=0
				echo "restart"
				restartapp
			fi
		fi
	
	done

}
keep_link(){
	initnode
	i=0
	while true
	do
		node=$(getnode)
		echo "node"=$node
		resp=$($testlink $node $localport)
		echo "resp"=$resp
		if [ "$resp" = "ok" ]; then
			if [ "$($pidapp)" ]; then
				let i+=1
				echo "i="$i

			else
				echo "start"		
			fi
		else
			echo "restart"

		fi
		sleep 30
	done
}
echo "test1"
case "$1" in
	start)
		startapp
	;;
	auto)
		auto_tcp
	;;
	keeplink)
		keep_link
	;;
esac

